package org.example.com.RocketMq.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.example.com.RocketMq.dto.UserCharge;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.UUID;

/*
    分布式事务
 */
@Slf4j
@Component
public class MQTXProducerService {
    private static final String TRAN_TOPIC = "TRAN_TOPIC";
    private static final String TRAN_TAG = "TRAN_TAG";
    private static final String TRAN_GROUP = "TRAN_GROUP";

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public TransactionSendResult sendHalfMsg(UserCharge userCharg){
        String transactionId = UUID.randomUUID().toString().replace("-","");

//        TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction(
//                TRAN_GROUP,
//                TRAN_TOPIC + ":" + TRAN_TAG,
//                new Message<Object>() {
//                    @Override
//                    public Object getPayload() {
//                        return userCharge;
//                    }
//                    @Override
//                    public MessageHeaders getHeaders() {
//                        Map<String, Object> transactionIdMap = new HashMap<>();
//                        transactionIdMap.put(RocketMQHeaders.TRANSACTION_ID, transactionId);
//                        MessageHeaders transHeader = new MessageHeaders(transactionIdMap);
//                        return transHeader;
//                    }
//                }, userCharge);
        TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction(
                TRAN_GROUP, TRAN_TOPIC+":"+TRAN_TAG,
                MessageBuilder.withPayload(userCharg).setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId).build(),
                userCharg);
        log.info("【发送半消息】sendResult={}", JSON.toJSONString(sendResult));
        return sendResult;
    }
}
